package org.wanliu.youwei.http.proxy;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;

import org.wei.utils.exception.LogHelper;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@WebServlet("/proxy")
public class HttpProxy extends HttpServlet {
	private static final long serialVersionUID = 2461505375316480023L;
	private static LogHelper logHelper = LogHelper.getInstance();
	private static Gson gson = new Gson();
	static {
		LogHelper.getClassnamefilters().clear();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		PrintWriter out = resp.getWriter();
		Client client = ClientBuilder.newClient();
		try {
			String url = req.getParameter("url");
			WebTarget target = client.target(url);
			Map<String, String[]> params = req.getParameterMap();
			for (Entry<String, String[]> entry : params.entrySet()) {
				String key = entry.getKey();
				String[] values = entry.getValue();
				if (!"url".equals(key) && !"cookies".equals(key)) {
					target = target.queryParam(key, values[0]);
				}
			}
			List<NewCookie> cookies = gson.fromJson(
					req.getParameter("cookies"),
					new TypeToken<List<NewCookie>>() {
					}.getType());
			Builder builder = target.request();
			if (cookies != null) {
				for (NewCookie cookie : cookies) {
					builder.cookie(cookie);
				}
			}
			Response response = builder.buildGet().invoke();
			ProxyResponse proxyResponse = new ProxyResponse();
			proxyResponse.setStatus(response.getStatus());
			proxyResponse.setEntity(response.readEntity(String.class));
			proxyResponse.setCookies(response.getCookies());
			response.close();
			out.print(gson.toJson(proxyResponse));
		} catch (Exception e) {
			ProxyResponse proxyResponse = new ProxyResponse();
			proxyResponse.setStatus(404);
			proxyResponse.setEntity(e.getMessage());
			out.print(gson.toJson(proxyResponse));
			logHelper.error(e, getClass());
		} finally {
			out.close();
		}

	}
}
